﻿using Frameworks;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class LoadScence : MonoBehaviour
{
    public Slider slider;

    private void Start()
    {
        Invoke("DelayLoadScene", 0.016f);
    }

    private void DelayLoadScene()
    {
        StartCoroutine(loadScence());
    }

    private IEnumerator loadScence()
    {
        int displayProgress = 0;
        AsyncOperation asyncOperation = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(GameManager.SceneMgr.CurScene);
        asyncOperation.allowSceneActivation = false;
        while (!asyncOperation.isDone)
        {
            if (asyncOperation.progress >= 0.9f)
            {
                displayProgress += 1;

                //Debug.Log("<color=red>" + displayProgress + " " + asyncOperation.progress + "</color>");

                if (displayProgress >= 100)
                {
                    asyncOperation.allowSceneActivation = true;
                }
            }
            else
            {
                displayProgress = (int)(asyncOperation.progress * 100);
            }

            Mathf.Clamp(displayProgress, 0, 100);
            SetLoadingPrecentage(displayProgress);

            yield return null;
        }
    }

    private void SetLoadingPrecentage(int num)
    {
        float x = num / 100f;
        slider.value = x;
    }

    private void Update()
    {
        LoadingText();
        LoadingSpinner();
    }

    #region LoadingText
    public Text loadingText;
    private float _lastUpdate = 0;
    private int _numElipses = 1;

    private void LoadingText()
    {
        if (_lastUpdate == 0 || Time.unscaledTime > (_lastUpdate + 0.3f))
        {
            string t = "Loading";
            for (int i = 0; i < _numElipses; i++)
            {
                t += ".";
            }
            loadingText.text = t;
            _numElipses = _numElipses == 3 ? 0 : _numElipses + 1;

            _lastUpdate = Time.unscaledTime;
        }
    }
    #endregion

    #region LoadingSpinner
    public Transform loadingSpinner;
    private Quaternion _targetRotation = Quaternion.AngleAxis(180, Vector3.forward);

    private void LoadingSpinner()
    {
        if (loadingSpinner.gameObject.activeSelf)
        {
            loadingSpinner.rotation = Quaternion.Slerp(loadingSpinner.rotation, _targetRotation, 0.05f);
            if (Quaternion.Angle(loadingSpinner.rotation, _targetRotation) < 1)
            {
                loadingSpinner.rotation = Quaternion.AngleAxis(0, Vector3.forward);
            }
        }
    }
    #endregion
}
